<?php
namespace app\command;

use app\model\BookContentsModel;
use app\model\OrderAftersalesModel;
use app\model\OrderItemsModel;
use app\model\OrderLogisticsModel;
use app\model\OrderReviewsModel;
use app\model\OrdersModel;
use app\model\ProductsModel;
use app\model\RedisModel;
use app\model\StatisticsModel;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

class UpdateBookChapterContent extends Command
{

    protected function configure()
    {
        $this->setName('更新物流轨迹')
            ->setDescription('批量处理订单的物流信息');
    }

    protected function execute(Input $input, Output $output)
    {
        // 获取所有章节数据
        $chapters = Db::name("book_contents")->select();

        foreach ($chapters as $chapter) {
            $chapter_id = $chapter['chapter_id'];
            $html = $chapter['chapter_content'];

            // 第三步：匹配特定结构的 <p> 并在其**前面**插入两个空段落
            $pattern = '/<p\s+style="text-align:\s*justify;\s*line-height:\s*2;">(?:\s*<span\b[^>]*>.*?<\/span>)*\s*<\/p>/is';
            $replacement = "\n" .
                '<p style="text-align: justify; line-height: 2;"><br></p>' . "\n" .
                '<p style="text-align: justify; line-height: 2;"><br></p>' . "\n" .
                '$0';

            // 执行替换
            $new_html = preg_replace($pattern, $replacement, $html);

            // 只有当内容确实发生了变化时才更新数据库
            if ($new_html !== $html) {
                $res = Db::name("book_contents")->where("chapter_id", $chapter_id)->update([
                    "chapter_content" => $new_html
                ]);

                if ($res) {
                    $output->writeln("章节 ID: {$chapter_id} 已更新");
                } else {
                    $output->writeln("章节 ID: {$chapter_id} 更新失败");
                }

                // 删除缓存
                $cacheKey = "chapter:content:id" . $chapter_id;
                $redisModel = new RedisModel();
                $delCache = $redisModel->delete($cacheKey);

                if ($delCache) {
                    $output->writeln("章节 ID: {$chapter_id} 缓存已清除");
                } else {
                    $output->writeln("章节 ID: {$chapter_id} 缓存清除失败或不存在");
                }
            } else {
                $output->writeln("章节 ID: {$chapter_id} 未匹配到目标内容，跳过");
            }
        }

        $output->writeln("处理完成！");
    }
}